class ChatController < ApplicationController

#  layout "main"
  before_filter :login?, :only => ["vulgar", "destroy_vulgar", "new_vulgar", "create_vulgar"]

  def index
    if session[:user_id]
      if current_user.ban_chat
        flash[:notice] = "ไม่สามารถใช้ห้องสนทนาได้ กรุณาติดต่อผู้ดูแลระบบ"
        redirect_to_root
      else
        @chat_user= ChatUser.new(:login=>current_user.login)
        @chat_user.save
        @chat_users= ChatUser.all
        @chat= Chat.last
      end
    else
      flash[:notice] = "กรุณาล็อกอินก่อนเข้าใช้งาน"
      redirect_to_root
    end
  end

  def vulgar
    @vulgars= Vulgar.all :order => "id DESC"
  end

  def destroy_vulgar
    Vulgar.destroy(params[:id])
    redirect_to :action => "vulgar"
  end

  def new_vulgar
    @vulgar= Vulgar.new
  end

  def create_vulgar
    Vulgar.create params[:vulgar]
    redirect_to :action => "vulgar"
  end

  def update
    t= []
    chats= Chat.all :conditions=>"id > #{params[:id]}", :order=>"created_at"
    chats.each do |chat|
      t << "$('#main').append(\"<div><span class='user'>#{chat.user.login}:</span> #{chat.message}</div>\")"
      t << "var textArea = document.getElementById('main');"
      t << "textArea.scrollTop = textArea.scrollHeight;"
    end
    t << "$('#last').text('#{Chat.last ? Chat.last.id : 0}')"
    if params[:num_users].to_i != ChatUser.count
      uu = []
      ChatUser.all.each do |u|
        uu << "<img src='/images/user.png' /> "
        uu << "<span style='position:relative; top:-3px;'>#{u.login}</span><br/>"
      end
      t << "$('#users').html(\"#{uu.join}\")"
      t << "$('#num_users').text('#{ChatUser.count}')"
    end
    render :text => t.join(";")
  end

  def broadcast
    unless params[:msg].blank?
      msg= params[:msg].dup
      Vulgar.all.each do |v|
        msg.gsub!(v.original,v.alternate)
      end
      Chat.create :user_id=>current_user.id, :message=>msg, :message_original=>params[:msg],
        :ip=>request.env['REMOTE_ADDR']
    end
    render :text => "ok"
  end
end
